<template>
  <div>
    <!-- {{qid}} -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-model-item label="题干" prop="questionName">
        <a-textarea v-model="form.questionName" rows="4" style="resize: none" />
        <span style="color:#aaa;"
          >问答题为开放性作答，没有标准答案，需要人工阅卷</span
        >
      </a-form-model-item>
      <a-form-model-item label="题干图片">
        <a-upload
          :action="URL + '/uploadImage'"
          list-type="picture-card"
          :file-list="questionImgList"
          :headers="token"
          @preview="handlePreview"
          @change="questionHandleChange"
        >
          <div v-if="questionImgList.length < 3">
            <a-icon type="plus" />
            <div class="ant-upload-text">添加图片</div>
          </div>
        </a-upload>
        <span class="not">
          允许上传图片的格式为jpg、jpeg、gif、bmp、png，最多上传3张图片，大小限制5M以内
        </span>
        <a-modal
          :visible="previewVisible"
          :footer="null"
          @cancel="handleCancel"
        >
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-model-item>

      <a-form-model-item label="答案解析">
        <a-textarea
          v-model="form.questionAnalysis"
          rows="4"
          style="resize: none"
        />
        <a-upload
          style="margin-top: 10px"
          :action="URL + '/uploadImage'"
          list-type="picture-card"
          :file-list="answerImgList"
          :headers="token"
          @preview="handlePreview"
          @change="answerHandleChange"
        >
          <div>
            <a-icon type="plus" />
            <div class="ant-upload-text">添加图片</div>
          </div>
        </a-upload>
        <span class="not">
          允许上传图片的格式为jpg、jpeg、gif、bmp、png，最多上传3张图片，大小限制5M以内
        </span>
      </a-form-model-item>
      <a-form-model-item label="标签">
        <template v-for="(tag, index) in tags">
          <a-tooltip v-if="tag.length > 10" :key="tag" :title="tag">
            <a-tag
              :key="tag"
              color="#f50"
              :closable="index !== -1"
              @close="() => handleClose(tag)"
            >
              {{ `${tag.slice(0, 10)}...` }}
            </a-tag>
          </a-tooltip>
          <a-tag
            v-else
            :key="tag"
            :color="tag.length > 5 ? '#87d068' : '#108ee9'"
            :closable="index !== -1"
            @close="() => handleClose(tag)"
          >
            {{ tag }}
          </a-tag>
        </template>
        <a-input
          v-if="inputVisible"
          ref="input"
          type="text"
          size="small"
          :style="{ width: '78px' }"
          :value="inputValue"
          @change="handleInputChange"
          @blur="handleInputConfirm"
          @keyup.enter="handleInputConfirm"
        />
        <a-tag
          v-else
          style="background: #fff; borderStyle: dashed;"
          @click="showInput"
        >
          <a-icon type="plus" /> 新建标签
        </a-tag>
        <br />
        <a-button type="primary" style="margin-top: 20px" @click="postSave"
          >保存问答题</a-button
        >
        <a-button type="" style="margin-top: 20px; margin-left: 10px"
          >保存并继续</a-button
        >
        <a-button type="" style="margin-top: 20px; margin-left: 10px"
          >取消</a-button
        >
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import UpdateURL from "../../../../axios.js";
// 获取Base64的内容
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  props: ["qid"],
  inject: ["getAnswer"],
  data() {
    return {
      URL: "",
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      other: "",
      form: {
        type: 5, // 表示这个是判断题
        questionName: "",
        questionImg: "",
        questionAnswer: "",
        questionBankId: this.qid, // 题库id 需要父组件 传值过来
        questionAnalysis: "", // 答案解析
        questionAnalysisImg: "", // 答案解析图片
        questionTags: ""
      },
      previewVisible: false,
      previewImage: "",
      questionImgList: [], // 题干图片
      answerImgList: [], // 解析图片
      tags: [], // 标签
      rules: {
        questionName: [
          { required: true, message: "请输入题干!", trigger: "blur" },
          { max: 300, message: "最多输入300个字符!", trigger: "change" }
        ]
      },
      token: {
        Authorization: localStorage.getItem("token")
      },
      inputVisible: false,
      inputValue: ""
    };
  },
  created() {
    this.URL = UpdateURL.posUrl;
  },
  methods: {
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    questionHandleChange({ fileList }) {
      this.questionImgList = fileList;
      console.log(this.questionImgList);
    },
    answerHandleChange({ fileList }) {
      this.answerImgList = fileList;
      console.log(this.answerImgList);
    },
    onChange(e) {
      console.log("radio checked", e.target.value);
      console.log(this.form.questionAnswer);
    },
    postSave() {
      // 处理题干图片
      let questionImgLen = this.questionImgList.length;
      for (let i = 0; i < questionImgLen; i++) {
        if (i < questionImgLen - 1) {
          if (this.questionImgList[i].response.code == 200)
            this.form.questionImg += this.questionImgList[i].response.msg + ",";
        } else {
          if (this.questionImgList[i].response.code == 200)
            this.form.questionImg += this.questionImgList[i].response.msg;
        }
      }
      this.form.questionImg.toString();

      // 处理解析图片
      let answerImglen = this.answerImgList.length;
      for (let i = 0; i < answerImglen; i++) {
        if (i < answerImglen - 1) {
          if (this.answerImgList[i].response.code == 200)
            this.form.questionAnalysisImg +=
              this.answerImgList[i].response.msg + ",";
        } else {
          if (this.answerImgList[i].response.code == 200)
            this.form.questionAnalysisImg += this.answerImgList[i].response.msg;
        }
      }
      this.form.questionAnalysisImg.toString();

      // 处理标签
      let str = "";
      let len = this.tags.length;
      // 拼接字符串
      for (let i = 0; i < len; i++) {
        if (i < len - 1) {
          str = str + this.tags[i] + ",";
        } else {
          str = str + this.tags[i] + "";
        }
      }
      this.form.questionTags = str.toString();
      console.log(this.form);
      this.$axios
        .post("/create/question/detail", this.form, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })
        .then(res => {
          if (res.data.code == 200) {
            this.form.questionName = "";
            this.form.questionImg = "";
            this.form.questionAnswer = [];
            this.form.questionAnalysis = ""; // 答案解析
            this.form.questionAnalysisImg = ""; // 答案解析图片
            this.form.questionTags = "";
            this.questionImgList = []; // 题干图片
            this.answerImgList = []; // 解析图片
            this.tags = []; // 标签
            this.getAnswer();
            this.$message.success(res.data.msg);
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    handleClose(removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      this.tags = tags;
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },

    handleInputChange(e) {
      this.inputValue = e.target.value;
    },

    handleInputConfirm() {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      console.log(tags);
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: ""
      });
    }
  }
};
</script>

<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.not {
  font-size: 12px;
  color: #b4b4b4;
}
</style>
